﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace psafth.RCTiming.Main.Pages.Dialogs
{
    /// <summary>
    /// Interaction logic for AddDriverDialog.xaml
    /// </summary>
    public partial class AddDriverDialog : Window
    {
        private bool firstNameValid = false;
        private bool lastNameValid = false;
        private bool emailValid = true;
        private bool licenceNumberValid = false;
        private bool clubValid = false;

        private UserPage _userPage = null;

        public DBContext DbContext
        {
            get
            {
                return this._userPage.MainWindow.DbContext;
            }
            set
            {
                this._userPage.MainWindow.DbContext = value;
            }
        }

        public AddDriverDialog(UserPage up)
        {
            _userPage = up;

            InitializeComponent();
            FetchAndBindClubs();
            ValidateBtnSave();
        }

        public void FetchAndBindClubs()
        {
            cbClub.ItemsSource = DbContext.Clubs.ToList();
            cbClub.DisplayMemberPath = "FullName";
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cbClub.SelectedItem != null)
                {
                    if (cbClub.SelectedItem is Club)
                    {
                        Club selectedClub = (Club)cbClub.SelectedItem;

                        string lNo = ((string)lblLicencePrefix.Content) + tbLicenceNumber.Text.Trim();

                        DbContext.Clubs.FirstOrDefault(c => c.Id == selectedClub.Id).Drivers.Add(new Driver() { FirstName = tbFirstName.Text, LastName = tbLastName.Text, EmailAddress = tbEmail.Text, LicenceNumber = lNo });

                        DbContext.SaveChanges();

                        _userPage.UpdateUserDataGrid();

                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Datafel för vald klubb", "Fel", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Datafel för vald klubb", "Fel", MessageBoxButton.OK, MessageBoxImage.Error);
                    // TODO: <3 Linda
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ett fel inträffade när förare skulle sparas", "Fel", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void cbClub_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cbClub.SelectedItem != null)
                {
                    if (cbClub.SelectedItem is Club)
                    {
                        Club selectedClub = (Club)cbClub.SelectedItem;
                        tbLicenceNumber.IsEnabled = true;
                        cbClub.Text = selectedClub.FullName;
                        lblLicencePrefix.Content = selectedClub.LicencePrefix;
                        lblValidationClub.Visibility = System.Windows.Visibility.Collapsed;
                        clubValid = true;
                    }
                }
                else
                {
                    tbLicenceNumber.IsEnabled = false;
                    lblLicencePrefix.Content = string.Empty;

                    lblValidationClub.Visibility = System.Windows.Visibility.Visible;
                    clubValid = false;

                    if (!string.IsNullOrWhiteSpace(cbClub.Text))
                    {
                        MessageBoxResult result = MessageBox.Show(string.Format("Klubben {0} hittades inte. Vill du lägga till den?", cbClub.Text), "Information", MessageBoxButton.YesNo, MessageBoxImage.Information);

                        switch (result)
                        {
                            case MessageBoxResult.No:
                                cbClub.Text = string.Empty;
                                break;

                            case MessageBoxResult.Yes:
                                Dialogs.AddClubDialog prd = new Dialogs.AddClubDialog(this);
                                prd.Owner = this;
                                prd.ShowDialog();
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO: Implement logging
            }

            ValidateBtnSave();
        }

        public void cbClub_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (cbClub.SelectedItem != null)
                {
                    if (cbClub.SelectedItem is Club)
                    {
                        Club selectedClub = (Club)cbClub.SelectedItem;
                        tbLicenceNumber.IsEnabled = true;
                        lblLicencePrefix.Content = selectedClub.LicencePrefix;
                        lblValidationClub.Visibility = System.Windows.Visibility.Collapsed;
                        clubValid = true;
                    }
                }
                else
                {
                    tbLicenceNumber.IsEnabled = false;
                    lblLicencePrefix.Content = string.Empty;
                    lblValidationClub.Visibility = System.Windows.Visibility.Visible;
                    clubValid = false;
                }
            }
            catch (Exception ex)
            {
            }

            ValidateBtnSave();
        }

        private void tbFirstName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbFirstName.Text))
            {
                lblValidationFirstName.Visibility = System.Windows.Visibility.Collapsed;
                firstNameValid = true;
            }
            else
            {
                lblValidationFirstName.Visibility = System.Windows.Visibility.Visible;
                firstNameValid = false;
            }

            ValidateBtnSave();
        }

        private void tbLastName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbLastName.Text))
            {
                lblValidationLastName.Visibility = System.Windows.Visibility.Collapsed;
                lastNameValid = true;
            }
            else
            {
                lblValidationLastName.Visibility = System.Windows.Visibility.Visible;
                lastNameValid = false;
            }

            ValidateBtnSave();
        }

        private void tbEmail_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbEmail.Text))
            {
                if (IsEmailValid(tbEmail.Text))
                {
                    lblValidationEmail.Visibility = System.Windows.Visibility.Collapsed;
                    emailValid = true;
                }
                else
                {
                    lblValidationEmail.Visibility = System.Windows.Visibility.Visible;
                    emailValid = false;
                }
            }
            else
            {
                lblValidationEmail.Visibility = System.Windows.Visibility.Collapsed;
                emailValid = true;
            }

            ValidateBtnSave();
        }

        private void tbLicenceNumber_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbLicenceNumber.Text))
            {
                string lNo = ((string)lblLicencePrefix.Content) + tbLicenceNumber.Text.Trim();

                Driver driver = DbContext.Drivers.FirstOrDefault(d => d.LicenceNumber == lNo);

                if (driver != null)
                {
                    lblValidationLicenceNumber.Visibility = System.Windows.Visibility.Visible;
                    licenceNumberValid = false;
                }
                else
                {
                    lblValidationLicenceNumber.Visibility = System.Windows.Visibility.Collapsed;
                    licenceNumberValid = true;
                }
            }
            else
            {
                lblValidationLicenceNumber.Visibility = System.Windows.Visibility.Visible;
                licenceNumberValid = false;
            }

            ValidateBtnSave();
        }

        private void ValidateBtnSave()
        {
            btnSave.IsEnabled = false;

            if (firstNameValid && lastNameValid && emailValid && clubValid && licenceNumberValid)
                btnSave.IsEnabled = true;
        }

        private bool IsEmailValid(string emailaddress)
        {
            return Regex.IsMatch(emailaddress, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
    }
}
